package cn.lf.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.lf.constant.ResponseCodeEnum;
import cn.lf.dto.sys.user.*;
import cn.lf.entity.SysUser;
import cn.lf.exception.SelfException;
import cn.lf.mapper.SysUserMapper;
import cn.lf.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author guoyy
 * @since 2024-04-01
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    public IPage<UserListGetRepDTO> queryUserPage(UserListGetReqDTO params) {

        Page<UserListGetRepDTO> page = new Page<>(params.getCurrentPage(),params.getPageSize());

        return baseMapper.selectUserPage(page,params);
    }

    @Override
    public void setUserStatus(UserStatusSetReqDTO userStatusSetReqDTO) {

        SysUser sysUser  = (SysUser) SecurityUtils.getSubject().getPrincipal();

        LambdaUpdateWrapper<SysUser> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        lambdaUpdateWrapper.set(SysUser::getStatus,userStatusSetReqDTO.getStatus());

        lambdaUpdateWrapper.set(SysUser::getUpdateTime,new Date());

        lambdaUpdateWrapper.set(SysUser::getUpdateByName,sysUser.getUserName());

        lambdaUpdateWrapper.eq(SysUser::getUserId,userStatusSetReqDTO.getUserId());

        baseMapper.update(null,lambdaUpdateWrapper);

    }

    @Override
    public void setUserInfo(UserInfoSetReqDTO userInfoSetReqDTO) {

        SysUser updateUser = (SysUser) SecurityUtils.getSubject().getPrincipal();

        SysUser sysUser = baseMapper.selectById(userInfoSetReqDTO.getUserId());

        if (Objects.isNull(sysUser)){
            throw new SelfException(ResponseCodeEnum.SYS_ERROR.getCode(),"用户未找到");
        }

        BeanUtils.copyProperties(userInfoSetReqDTO,sysUser);
        sysUser.setUpdateTime(new Date());
        sysUser.setUpdateByName(updateUser.getFullName());

        baseMapper.updateById(sysUser);


    }

    @Override
    public UserInfoGetRepDTO getUserInfoById(String userId) {

        UserInfoGetRepDTO result = new UserInfoGetRepDTO();

        SysUser sysUser = baseMapper.selectById(userId);

        BeanUtils.copyProperties(sysUser,result);

        result.setBirthday(DateUtil.format(sysUser.getBirthday(),"yyyy-MM-dd"));

        return result;
    }
}
